var fs = require('fs');
var url = require('url');
var http = require('http');
var async = require('async');
const path = require('path');
var request = require('request');
const { app, ipcMain, dialog, BrowserWindow } = require('electron')

String.prototype.isNumber = function(){
    var reg = /^[0-9]+\.?[0-9]*$/;
    return reg.test(this)
}

String.prototype.format = function () {
    if (arguments.length == 0)
        return null;

    var str = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}

function download(baseurl,src,dst,cb){
    var url = baseurl + src;
    var s = fs.createWriteStream(dst);
    request(url).pipe(s).on('close',(err)=>{
        cb(err);
    })
}

function preparedownload(baseurl,files,cb){
    var items = new Array();
    async.forEach(files,(f,cb)=>{
        var namewithoutext = f.name.substring(0,f.name.length - f.suffix.length);
        var tags = [];
        var arr = namewithoutext.split('_');
        for(var i = 0; i < arr.length; i++){
            if(!arr[i].isNumber() && arr[i].length > 0){
                tags[i] = arr[i];
            }
        }
        var item = {
            id:f.id,
            name:f.name,
            url:'{0}{1}{2}'.format(baseurl,f.id,f.suffix),
            size:f.size,
            tags:tags,
            count:0,
            suffix:f.suffix,
        }
        items.push(item);
        cb(null);
    },(err)=>{
        cb(err,items);
    })
}

function downloadall(baseurl,files,dir,onfinish,msg){
    async.waterfall([
        (callback) =>{
            preparedownload(baseurl,files,(err,items) =>{
                callback(err,items);
            })
        },
        (items,callback) =>{
            var map = new Map();
            for(var i = 0; i < items.length; i++){
                var filename = items[i].tags.join('_');
                var index = 0;
                if(map.has(filename)){
                    index = map.get(filename) + 1;
                    items[i].count = index;
                }else{
                    items[i].count = 1;
                    index = 1;
                }
                map.set(filename,index);
                items[i].index = index;
            }

            for(var i = 0; i < items.length; i++){
                var suffix = items[i].count > 1 ? '_'+ items[i].index.toString().padStart(2,0) : '';
                var filename = items[i].tags.join('_') + suffix + items[i].suffix;
                items[i].filename = path.join(dir,filename);
            }

            callback(null,items);
        },
        (items,callback) =>{
            async.forEach(items,(i,cb)=>{
                download(baseurl,i.id+i.suffix,i.filename,(err)=>{
                    cb(err);
                })
            },(err)=>{
                onfinish(err,items.length);
            })
        }
    ])    
}

module.exports = {
    download,
    downloadall,
}